package com.itheima.jdbcdemo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private JDBCUtils() {
    }

    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
            BufferedReader bw = new BufferedReader(new InputStreamReader(inputStream));
            String[] split = bw.readLine().split("=");
            String driver = split[1];
            String[] split1 = bw.readLine().split("=");
            url = split1[1];
            String[] split2 = bw.readLine().split("=");
            username = split2[1];
            String[] split3 = bw.readLine().split("=");
            password = split3[1];
            /*Properties p = new Properties();
            p.load(inputStream);
            String driver = p.getProperty("driver");
            url = p.getProperty("url");
            username = p.getProperty("username");
            password = p.getProperty("password");*/
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() {
        //
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }


    //是否资源
    public static void close(Connection conn, Statement stat, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, Statement stat) {
        close(conn, stat, null);
    }
}
